import { h } from '@knno/dom/jsx';
import { dom } from '@knno/dom';
import { InlineEditor } from '../inlineEditor';
import SVGTable from '@mdi/svg/svg/table.svg';
import SVGImg from '@mdi/svg/svg/image-outline.svg';
import { popupMenu } from '../../tools/ui';
import { DICT } from '../../dict';

export function paragraphOnContextMenu(editor: InlineEditor, p: HTMLParagraphElement, evt: MouseEvent) {
	if (p.parentElement === editor.elems()[0]) {
		const menu = [
			{ icon: SVGTable, value: DICT.insertTable },
			{ icon: SVGImg, value: DICT.insertImage },
		];
		popupMenu({ refer: dom.wrap(p), menu, pos: { x: evt.x, y: evt.y }, width: 180 }, (value) => {
			if (value === DICT.insertTable) {
				editor.insertTable();
			} else if (value === DICT.insertImage) {
				editor.insertImage();
			}
		});
	}
}

export function paragraphOnKeyDown(editor: InlineEditor, p: HTMLElement, evt: KeyboardEvent) {
	if (evt.key === 'Enter' && !evt.shiftKey) {
		evt.preventDefault();
		const sel = window.getSelection();
		if (!sel || sel.rangeCount === 0) return;
		const range = sel.getRangeAt(0);
		if (!range.collapsed) {
			range.deleteContents();
			range.collapse(true);
		}
		range.setEnd(p, p.childNodes.length);
		const splitContent = range.extractContents();
		if (p.childNodes.length === 0) {
			range.selectNodeContents(p);
			range.collapse(true);
			range.insertNode(document.createElement('br'));
		}
		range.setStartAfter(p);
		range.collapse(true);
		const validContents = Array.from(splitContent.childNodes).filter(
			(c) => !(c.nodeName === '#text' && c.textContent === '')
		);
		const newParagraph = document.createElement('p');
		range.insertNode(newParagraph);
		if (validContents.length === 0) {
			validContents.push(document.createElement('br'));
		}
		validContents.forEach((item) => {
			range.selectNodeContents(newParagraph);
			range.collapse(true);
			range.insertNode(item);
		});
		range.collapse(true);
		editor.emitChange();
	} else if (evt.key === 'Backspace') {
		const sel = window.getSelection();
		if (!sel || sel.rangeCount === 0) return;
		const range = sel.getRangeAt(0);
		if (!range.collapsed) {
			return;
		}
		if (range.startContainer === p.firstChild && range.startOffset === 0) {
			if (p.previousElementSibling?.nodeName === 'DIV' || p.previousElementSibling?.nodeName === 'TABLE') {
				evt.preventDefault();
				range.selectNode(p.previousElementSibling);
			}
		} else {
			const children = [...p.childNodes].filter((c) => !(c.nodeName === '#text' && c.textContent === ''));
			if (children.length === 0) {
				range.selectNodeContents(p);
				range.insertNode(document.createElement('br'));
				range.collapse();
				evt.preventDefault();
			} else if (children[0].nodeName === 'BR') {
				if (p.previousElementSibling === null) {
					evt.preventDefault();
				}
			}
		}
		editor.emitChange();
	}
}
